package com.clas.liu.myapplication.model.impl;

import android.os.Handler;
import android.util.Log;

import com.clas.liu.myapplication.model.entity.Register.RegisterRoot;
import com.clas.liu.myapplication.model.entity.user.UserData;
import com.clas.liu.myapplication.model.event.RegisterEvent;
import com.clas.liu.myapplication.model.i.IRegisterModel;
import com.clas.liu.myapplication.network.NetworkInterfaces;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by liu on 2019/4/25.
 */

public class RegisterModel extends BaseModel implements IRegisterModel {

    public RegisterModel(Handler handler) {
        super(handler);
    }

    @Override
    public void register(UserData userData, String pwd) {
        Callback callback = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                RegisterEvent event = new RegisterEvent();
                event.setWhat(RegisterEvent.REGISTER_FAIL);
                postEvent(event);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    Gson gson = new Gson();
                    RegisterRoot root = gson.fromJson(response.body().string(),RegisterRoot.class);
                    RegisterEvent event = new RegisterEvent();
                    event.setWhat(RegisterEvent.REGISTER_OK);
                    event.setRegisterRoot(root);
                    postEvent(event);
                } else
                    onFailure(call, new IOException(response.body().string()));

            }
        };
        Gson gson = new Gson();
        String user = gson.toJson(userData);
        interfaces.register(user,pwd,callback);
    }

    @Override
    protected NetworkInterfaces getNetworkInterface() {
        return new NetworkInterfaces();
    }
}
